package pannel.order;

import utils.JDBCUtils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;

public class OrderDao {
    private static final String TABLE_NAME = "`order`";

    // 分页查询所有订单(管理员用)
    public List<Order> pageQueryAll(String searchText, int page, int pageSize) throws SQLException {
        String sql = "SELECT o.*, u.username as user_name, p.name as product_name " +
                    "FROM " + TABLE_NAME + " o " +
                    "LEFT JOIN user u ON o.user_id = u.id " +
                    "LEFT JOIN product p ON o.product_id = p.id";
        if (searchText != null && !searchText.trim().isEmpty()) {
            sql += " WHERE u.username LIKE ? OR p.name LIKE ?";
        }
        sql += " ORDER BY o.create_time DESC LIMIT ? OFFSET ?";

        List<Object> params = new ArrayList<>();
        if (searchText != null && !searchText.trim().isEmpty()) {
            params.add("%" + searchText + "%");
            params.add("%" + searchText + "%");
        }
        params.add(pageSize);
        params.add((page - 1) * pageSize);

        ResultSet rs = (ResultSet) JDBCUtils.execute(sql, params.toArray());
        List<Order> orders = new ArrayList<>();
        while (rs.next()) {
            orders.add(mapResultSetToOrder(rs));
        }
        return orders;
    }

    // 分页查询用户订单
    public List<Order> pageQueryByUser(Integer userId, int page, int pageSize) throws SQLException {
        String sql = "SELECT o.*, u.username as user_name, p.name as product_name " +
                    "FROM " + TABLE_NAME + " o " +
                    "LEFT JOIN user u ON o.user_id = u.id " +
                    "LEFT JOIN product p ON o.product_id = p.id " +
                    "WHERE o.user_id = ? " +
                    "ORDER BY o.create_time DESC LIMIT ? OFFSET ?";

        ResultSet rs = (ResultSet) JDBCUtils.execute(sql, userId, pageSize, (page - 1) * pageSize);
        List<Order> orders = new ArrayList<>();
        while (rs.next()) {
            orders.add(mapResultSetToOrder(rs));
        }
        return orders;
    }

    // 获取总记录数
    public int getTotalCount(String searchText) throws SQLException {
        String sql = "SELECT COUNT(*) as total FROM " + TABLE_NAME + " o " +
                    "LEFT JOIN user u ON o.user_id = u.id " +
                    "LEFT JOIN product p ON o.product_id = p.id";
        if (searchText != null && !searchText.trim().isEmpty()) {
            sql += " WHERE u.username LIKE ? OR p.name LIKE ?";
            ResultSet rs = (ResultSet) JDBCUtils.execute(sql, 
                "%" + searchText + "%", 
                "%" + searchText + "%");
            return rs.next() ? rs.getInt("total") : 0;
        }
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql);
        return rs.next() ? rs.getInt("total") : 0;
    }

    // 获取用户订单总数
    public int getUserOrderCount(Integer userId) throws SQLException {
        String sql = "SELECT COUNT(*) as total FROM " + TABLE_NAME + " WHERE user_id = ?";
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql, userId);
        return rs.next() ? rs.getInt("total") : 0;
    }

    // 创建订单
    public boolean createOrder(Order order) throws SQLException {
        String sql = "INSERT INTO " + TABLE_NAME + " (user_id, product_id, quantity, total_price, status, create_time) " +
                    "VALUES (?, ?, ?, ?, ?, ?)";
        return (int) JDBCUtils.execute(sql, 
            order.getUserId(),
            order.getProductId(),
            order.getQuantity(),
            order.getTotalPrice(),
            order.getStatus(),
            new java.sql.Timestamp(order.getCreateTime().getTime())) > 0;
    }

    // 更新订单状态
    public boolean updateStatus(Integer orderId, String status) throws SQLException {
        String sql = "UPDATE " + TABLE_NAME + " SET status = ? WHERE id = ?";
        return (int) JDBCUtils.execute(sql, status, orderId) > 0;
    }

    // 根据ID获取订单
    public Order getOrderById(Integer orderId) throws SQLException {
        String sql = "SELECT o.*, u.username as user_name, p.name as product_name " +
                    "FROM " + TABLE_NAME + " o " +
                    "LEFT JOIN user u ON o.user_id = u.id " +
                    "LEFT JOIN product p ON o.product_id = p.id " +
                    "WHERE o.id = ?";
        
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql, orderId);
        if (rs.next()) {
            return mapResultSetToOrder(rs);
        }
        return null;
    }

    private Order mapResultSetToOrder(ResultSet rs) throws SQLException {
        return Order.builder()
                .id(rs.getInt("id"))
                .userId(rs.getInt("user_id"))
                .productId(rs.getInt("product_id"))
                .quantity(rs.getInt("quantity"))
                .totalPrice(rs.getDouble("total_price"))
                .status(rs.getString("status"))
                .createTime(rs.getTimestamp("create_time"))
                .userName(rs.getString("user_name"))
                .productName(rs.getString("product_name"))
                .build();
    }
} 